package org.aeon.fasttasks.core.recorder;


import org.aeon.fasttasks.core.util.CsvUtils;
import org.aeon.fasttasks.core.util.DateUtil;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author aeon
 * @createTime 2025/08/01  16:24
 * @description 异步Csv记录器
 */
public class AsyncCsvRecorder extends AbstractCsvRecorder implements Runnable, Closeable {

    private final static Logger log = LoggerFactory.getLogger(AsyncCsvRecorder.class);

    /**
     * 最大刷新间隔(ms)
     */
    private static final long FLUSH_INTERVAL = 500;

    private final BlockingQueue<Record> recordQueue;

    private final AtomicBoolean running;

    /**
     * 批量写入大小
     */
    private int batchSize;

    private long lastFlushTime;


    public AsyncCsvRecorder(String filePath, List<String> headers,
                            int queueSize, int batchSize, boolean recordingTime,
                            ThreadPoolTaskExecutor bossTasksExecutor) {
        super(filePath, headers, recordingTime);

        this.recordQueue = new ArrayBlockingQueue<>(Math.min(10000, queueSize));
        this.batchSize = batchSize;
        this.running = new AtomicBoolean(true);

        this.lastFlushTime = System.currentTimeMillis();

        bossTasksExecutor.submit(this);
    }

    @Override
    public void record(Object... contents) {
        if (!running.get()) {
            throw new RuntimeException("记录器已关闭");
        }

        if (contents == null || contents.length == 0) {
            return;
        }

        try {
            // 使用带超时的offer防止永久阻塞
            boolean success = recordQueue.offer(
                    new Record(Arrays.stream(contents).map(Object::toString).toList()),
                    100, TimeUnit.MILLISECONDS
            );

            if (!success) {
                log.info("日志队列已满，记录已删除");
                // 这里可以添加重试或记录错误策略
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("记录器中断: {}", e.getMessage(), e);
        }
    }

    public int getQueueSize() {
        return recordQueue.size();
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = Math.max(1, batchSize);
    }

    @Override
    public void close() {
        running.set(false);
    }

    @Override
    @SuppressWarnings("all")
    public void run() {
        try {
            Path path = Paths.get(filePath);
            CsvUtils.ensureDirectoryExists(path);

            while (running.get() || !recordQueue.isEmpty()) {
                List<Record> batch = new ArrayList<>(batchSize);

                // 带超时的批量获取
                recordQueue.drainTo(batch, batchSize);

                if (batch.isEmpty()) {
                    // 检查是否达到最大刷新间隔
                    if (System.currentTimeMillis() - lastFlushTime > FLUSH_INTERVAL) {
                        Thread.sleep(10);
                    }
                    continue;
                }

                processBatch(path, batch);
                lastFlushTime = System.currentTimeMillis();
            }

            // 最终刷新剩余记录
            if (!recordQueue.isEmpty()) {
                List<Record> finalBatch = new ArrayList<>();
                recordQueue.drainTo(finalBatch);
                processBatch(path, finalBatch);
            }
        } catch (Exception e) {
            log.error("CSV写入器错误: {}", e.getMessage(), e);
        }
    }

    private synchronized void processBatch(Path path, List<Record> batch) {
        try (CSVPrinter csvPrinter = CsvUtils.createCsvPrinter(path)) {
            handleHeader(csvPrinter);
            // 写入批量内容
            CsvUtils.writeRecords(csvPrinter, batch.stream().map(record -> {
                List<String> recordToWrite = new ArrayList<>(record.getContents());
                if (recordingTime) {
                    recordToWrite.add(DateUtil.formatTimestamp(record.getTimestamp()));
                }
                return recordToWrite;
            }).toList());

        } catch (IOException e) {
            log.error("写入CSV失败: {}", e.getMessage());
        }
    }
}
